#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bottle import Bottle, run,get,post,request,static_file,redirect
from beaker.middleware import SessionMiddleware
import json
app = Bottle()
msUsername = ''
msEquipmentid=''
session_opts = {
   'session.type':'file',              #以文件的方式保存session
   'session.cookei_expires':300,       #session过期时间为300秒
   'session.data_dir':'/tmp/sessions_dir', #session保存目录
   'session.auto':True               #自动保存session
    }

gun_dict={'100':'手枪','200':'步枪','300':'机关枪','400':'西瓜刀','500':'手榴弹'}
guai_dict={'10':'海底怪兽格斯拉','20':'魔王兽','30':'火山怪鸟'}

@app.get('/')
@app.get('/index')
def index():
    return {'Code':'0','Message': '访问首页，请先登录!'}

@app.post('/login')
def login():
    msUsername = request.json.get('username')
    sPassword = request.json.get('password')
    print(msUsername,sPassword)
    if msUsername==sPassword:
        ssSession = request.environ.get('beaker.session')

        ssSession['user'] = msUsername
        ssSession.save


        return {'Code':'0','Message': '登录成功，请选择武器!','Data':gun_dict}

    else:
        return {'Code':'-1','Message': '用户登录异常!'}


@app.post('/selectEq')
def selectEq():

    msEquipmentid = request.json.get('equipmentid')
    print(msEquipmentid)
    ssSession = request.environ.get('beaker.session')

    if msEquipmentid in gun_dict.keys():
        if str(msEquipmentid).isdigit():
            ssSession['equipmentid']=msEquipmentid
            ssSession.save
            return {'equipmentid':msEquipmentid,'Message':'你选择的武器是:'+gun_dict.get(msEquipmentid)}
    else:
        return {'equipmentid':'-1','Message':'选择的武器错误！'}


@app.post('/kill')
def kill():
    sEnemyid = request.json.get('enemyid')
    msEquipmentid = request.json.get('equipmentid')
 
    if sEnemyid is None:
        return {'enemyid':'-1','Message':'请选择一个要PK的怪兽！'}
    if msEquipmentid is None:
        return  {'equipmentid':'-1','Message':'选择的武器错误！'}
    if msEquipmentid in ['100','200','300','500']:
        if sEnemyid in ['10','20','30']:
            return {'Code':'0','Message':'恭喜你，这局你赢了，你成功击败了怪兽:【 {}】！'.format(guai_dict.get(sEnemyid))}
        else:
            return {'Code':'-1','Message':'怪兽不存在！'}
    else:
         return {'Code':'0','Message':'你输了，你所选择的武器：{}，无法击败怪兽：{}'.format(gun_dict.get(msEquipmentid),guai_dict.get(sEnemyid))}

app = SessionMiddleware(app, session_opts)

if __name__ == '__main__':
    run(app=app, port=12356)
